import { _decorator, Component, easing, EventTouch, Input, Label, Node, Sprite, SpriteFrame, tween, Tween, UITransform, Vec2, Vec3 } from 'cc';
import { ControlCubeLoad } from './ControlCubeLoad';
import { CubeBgLoad } from './CubeBgLoad';
import { ResMgr } from '../Mgr/ResMgr';
import { AssetList, Global } from '../Global';
import { SingleCubeBg } from './SingleCubeBg';
import { GAMEDATA } from './GAMEDATA';
import { GameScene } from './GameScene';
import { ModelLoad } from './ModelLoad';
import { Tools } from '../Tools';
import { AudioMgr, SoundName } from '../Mgr/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('SingleControlCube')
/**
 * 单个操作的方块
 */
export class SingleControlCube extends Component {

    //移动层
    @property(Node)
    private MoveLoad: Node = null;

    //方块数组
    @property([Node])
    private CubeArray: Node[] = [];

    //
    private CubePos: { hor: number, ver: number }[] = [
        { hor: 0, ver: 0 },
        { hor: 0, ver: 1 },
        { hor: 1, ver: 0 },
        { hor: 1, ver: 1 },
    ]

    //起始位置
    private StarPos: Vec3 = new Vec3();

    //间距
    private Distance: number = 31;

    //我是否放置成功了
    public IsPutSucess: boolean = true;

    protected start(): void {

        this.node.children[0].setPosition(new Vec3(-this.Distance, -this.Distance));
        this.node.children[1].setPosition(new Vec3(-this.Distance, this.Distance));
        this.node.children[2].setPosition(new Vec3(this.Distance, -this.Distance));
        this.node.children[3].setPosition(new Vec3(this.Distance, this.Distance));

        this.MoveLoad.children[0].setPosition(new Vec3(-this.Distance + 10, -this.Distance + 10));
        this.MoveLoad.children[1].setPosition(new Vec3(-this.Distance + 10, this.Distance + 10));
        this.MoveLoad.children[2].setPosition(new Vec3(this.Distance + 10, -this.Distance + 10));
        this.MoveLoad.children[3].setPosition(new Vec3(this.Distance + 10, this.Distance + 10));

        this.node.on(Input.EventType.TOUCH_START, this.TouchStart, this);
        this.node.on(Input.EventType.TOUCH_MOVE, this.TouchMove, this);
        this.node.on(Input.EventType.TOUCH_END, this.TouchEnd, this);
        this.node.on(Input.EventType.TOUCH_CANCEL, this.TouchEnd, this);
    }

    //方块样式
    private CubeStyle: number[] = [];

    /**
     * 更新元素
     */
    public UpdateControlCube(_num: number) {
        Global.IsDebug && console.log("更新砖块数量", _num)
        let cube_arr: Node[] = this.CubeArray.concat();
        for (let cube of cube_arr) cube.active = false;

        this.CubeStyle = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4];

        for (let i = 0; i < _num; i++) {
            let ran_num: number = Math.floor(Math.random() * cube_arr.length);
            let ran_num1: number = Math.floor(Math.random() * this.CubeStyle.length);
            cube_arr[ran_num].active = true;
            cube_arr[ran_num].name = this.CubeStyle[ran_num1].toString();
            cube_arr[ran_num].getComponent(Sprite).spriteFrame = ResMgr.Instance.SpriteFrames[AssetList.SpriteFrame.Ele + this.CubeStyle[ran_num1].toString()];
            tween(cube_arr[ran_num]).set({ scale: new Vec3(0, 0) }).to(0.3, { scale: new Vec3(0.6, 0.6) }, { easing: easing.backOut }).start();
            cube_arr.splice(ran_num, 1);
            this.CubeStyle.splice(ran_num1, 1);
        }

        this.IsPutSucess = false;
    }
    /**
     * 开始点击
     */
    private TouchStart(_e: EventTouch) {
        if (this.IsPutSucess) return;
        AudioMgr.instance.PlayEffect(SoundName.Click);
        this.StarPos = this.node.getPosition();
    }

    /**
     * 移动
     */
    private TouchMove(_e: EventTouch) {
        if (this.IsPutSucess) return;
        for (let i = 0; i < 4; i++)this.node.children[i].active = false;
        //移动我得方块
        var pos: any = _e.getUILocation().add(new Vec2(0, 100));
        pos = GameScene.Instance.ControlCubeLoad.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(pos.x, pos.y, 0));
        this.node.setPosition(pos);
    }

    /**
     * 手指抬起
     */
    private TouchEnd(_e: EventTouch) {
        if (this.IsPutSucess) return;
        this.CheckEle();
        this.node.setPosition(this.StarPos)
        for (let i = 0; i < 4; i++)this.node.children[i].active = true;
    }

    //对应砖块
    public DoubleCube: { my: Node, change: Node }[] = [];

    /**
     * 判断砖块是否在位置上
     */
    public CheckEle() {
        let show_num: number = 0;
        this.DoubleCube = [];

        for (let i = 0; i < 4; i++) {
            if (this.CubeArray[i].active) {
                show_num++;
                let cubg_bg: Node = GameScene.Instance.ControlCubeLoad.getComponent(ControlCubeLoad).CubeBgLoad.getComponent(CubeBgLoad).CheckPutCube(this.MoveLoad.children[i].getWorldPosition());
                if (cubg_bg) {
                    show_num--;
                    this.DoubleCube.push({ my: this.CubeArray[i], change: cubg_bg });
                }
            }
        };

        Global.IsDebug && console.log('成功数量', show_num)

        if (show_num > 0) return;//有不能合成得失败

        for (let cubeinfor of this.DoubleCube) {
            cubeinfor.change.getComponent(SingleCubeBg).AddEle(Number(cubeinfor.my.name));
        }

        this.IsPutSucess = true;
        for (let cube of this.CubeArray) cube.active = false;


        AudioMgr.instance.PlayEffect(SoundName.Down);
        //操作步数减少
        GameScene.Instance.ControlCubeLoad.getComponent(ControlCubeLoad).AllUpdate();
        GameScene.Instance.CubeBgLoad.getComponent(CubeBgLoad).CheckDis();
        GameScene.Instance.ModelLoad.getComponent(ModelLoad).UpdateStep(-1);

    }

    /**
     * 我是否可以放的下
     */
    public CheckIamPutDown(): boolean {

        if (this.IsPutSucess) {//我是空得还没有更新，我返回我不能成功放下
            return false;
        } else {//用我得第一个显示得方块和棋盘上得方块进行对比
            let show_cube: Node[] = [];
            for (let cube of this.CubeArray) if (cube.active) show_cube.push(cube);

            let cubg_bg_arr: Node[][] = GameScene.Instance.CubeBgLoad.getComponent(CubeBgLoad).CubeArray.concat();

            for (let i = 0; i < cubg_bg_arr.length; i++) {
                for (let j = 0; j < cubg_bg_arr[i].length; j++) {
                    if (cubg_bg_arr[i][j].getComponent(SingleCubeBg).CubeInfo.ele == -1) {

                        let first_pos: { hor: number, ver: number } =
                        {
                            hor: i - this.CubePos[this.MoveLoad.children.indexOf(show_cube[0])].hor,
                            ver: j - this.CubePos[this.MoveLoad.children.indexOf(show_cube[0])].ver
                        }

                        let is_can: boolean = true;

                        console.log("显示数组", show_cube, i, j);
                        console.log("我的位置", i, j, this.CubePos[this.MoveLoad.children.indexOf(show_cube[0])]);
                        console.log("第一个位置", first_pos);

                        //判断其余得行不行
                        for (let k = 1; k < show_cube.length; k++) {
                            console.log("进来了", k)
                            let cube_pos: { hor: number, ver: number } = this.CubePos[this.MoveLoad.children.indexOf(show_cube[k])];

                            //
                            let hor_num: number = first_pos.hor + cube_pos.hor;
                            let ver_num: number = first_pos.ver + cube_pos.ver;

                            console.log(first_pos, cube_pos, hor_num, ver_num, "看看")

                            if (hor_num >= 0 && hor_num < Global.HorNum && ver_num >= 0 && ver_num < Global.VerNum) {

                                console.log(hor_num, ver_num, "检查得另几个是否是空位", cubg_bg_arr[hor_num][ver_num].getComponent(SingleCubeBg).CubeInfo.ele);

                                if (cubg_bg_arr[hor_num][ver_num].getComponent(SingleCubeBg).CubeInfo.ele != -1) {
                                    is_can = false;
                                }
                            } else {
                                is_can = false;
                            }
                        }

                        console.log("是否可以移除", is_can, i, j);

                        if (is_can) {
                            return true;
                        }

                    }
                }

            }

            return false;
        }

    }

}
